package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.AddressService;
import com.itheima.reggie.service.CartService;
import com.itheima.reggie.service.OrderService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private CartService cartService;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderMapper orderMapper;
    //将用户的购物车数据保存为订单
    @Override
    public void save(Order order) {
        //获取当前用户
        User user = UserHolder.get();
        //查询当前用户的购物车是否为空,如果是空返回错误信息
        List<Cart> cartList = cartService.findList();
        if (CollectionUtil.isEmpty(cartList)){
            throw new CustomException("购物车为空,无法下单");
        }
        //根据addressId查询用户收获地址信息,如果为空返回错误信息
        Address address = addressMapper.selectById(order.getAddressId());
        if (address == null){
            throw new CustomException("地址不存在,无法下单");
        }
        //组装订单明细数据,保存订单明细
        //1.主键(mybatis提高雪花算法)
        long orderId = IdWorker.getId();
        BigDecimal amount = new BigDecimal(0);//初始化金额为0
        for (Cart cart : cartList) {
            //2.新建一个订单明细,进行添加
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(cart.getName());
            orderDetail.setOrderId(orderId);
            orderDetail.setDishId(cart.getDishId());
            orderDetail.setSetmealId(cart.getSetmealId());
            orderDetail.setDishFlavor(cart.getDishFlavor());
            orderDetail.setNumber(cart.getNumber());
            orderDetail.setAmount(cart.getAmount());
            orderDetail.setImage(cart.getImage());
            //叠加金额  amount = amount + cart.getAmount()*cart.getNumber()
            amount=amount.add(cart.getAmount().multiply(new BigDecimal(cart.getNumber())));
            orderDetailMapper.insert(orderDetail);
        }
        //组装订单数据,保存订单
        order.setId(orderId);
        order.setNumber(String.valueOf(orderId));
        order.setStatus(1);
        order.setUserId(user.getId());
        order.setOrderTime(new Date());
        order.setCheckoutTime(new Date());  // todo 这里的支付未完善,所以没有支付时间
        order.setAmount(amount);
        order.setUserName(address.getConsignee());
        order.setPhone(address.getPhone());
        StringBuilder sb = new StringBuilder();//字符串拼接
        sb.append(StringUtils.isNotEmpty(address.getProvinceName()) ? address.getProvinceName():"");//三元
        sb.append(StringUtils.isNotEmpty(address.getCityName()) ? address.getCityName():"");
        sb.append(StringUtils.isNotEmpty(address.getDistrictName()) ? address.getDistrictName():"");
        sb.append(StringUtils.isNotEmpty(address.getDetail()) ? address.getDetail():"");
        order.setAddress(sb.toString());
        order.setConsignee(address.getConsignee());
        orderMapper.insert(order);
        //注意: 企业中大多情况下,先一表,再来多表,因为多表中会用到一表的主键

        //清空用户购物车
        cartService.delete();
    }
    //查询订单详细
    @Override
    public Page<Order> findByPage(Integer pageNum, Integer pageSize) {
        //构建查询条件
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId,UserHolder.get().getId());
        //设置排序(时间倒序)
        wrapper.orderByDesc(Order::getOrderTime);
        //构建分页条件
        Page<Order> page = new Page<>(pageNum,pageSize);
        //根据用户id分页查询菜品信息列表
        page = orderMapper.selectPage(page, wrapper);
        List<Order> orderList = page.getRecords();
        //遍历
        if (CollectionUtil.isNotEmpty(orderList)) {
            for (Order order : orderList) {
                //根据id查询订单详细
                LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(OrderDetail::getOrderId, order.getId());
                List<OrderDetail> orderDetailList = orderDetailMapper.selectList(wrapper1);
                order.setOrderDetails(orderDetailList);
            }
        }
        return page;
    }
    //分页查询订单
    @Override
    public Page<Order> findByPage2(Long number, Date beginTime, Date endTime, Integer pageNum, Integer pageSize) {
        //查询条件
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(number!= null,Order::getNumber,number);
        wrapper.ge(beginTime != null,Order::getOrderTime,beginTime);
        wrapper.le(endTime !=null,Order::getOrderTime,beginTime);
        //分页查询条件
        Page<Order> page = new Page<>(pageNum,pageSize);
        //根据number查询,比较时间大小
        page=orderMapper.selectPage(page,wrapper);
        List<Order> orderList = page.getRecords();
        //遍历
        if (CollectionUtil.isNotEmpty(orderList)) {
            for (Order order : orderList) {
                LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(OrderDetail::getOrderId, order.getId());
                List<OrderDetail> orderDetailList = orderDetailMapper.selectList(wrapper1);
                order.setOrderDetails(orderDetailList);
            }
        }
        return page;
    }
}
